package logic

import (
	"cart_srv/cart"
	"context"
	"rpc/goods"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddCartLogic) AddCart(req *types.AddCartRequest) (resp *types.ResMsgResponse, err error) {
	// todo: 添加购物车

	//模拟用户登录
	userId := 1

	//查询商品是否存在
	show, err := l.svcCtx.GoodsSrv.GoodsShow(l.ctx, &goods.GoodsShowRequest{GoodsId: int64(req.GoodsId)})
	if err != nil {

		return &types.ResMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	if show.GoodId == 0 {
		return &types.ResMsgResponse{
			Cre:  -2,
			Msg:  "商品不存在",
			Data: nil,
		}, err
	}

	//查询库存
	stock, err := l.svcCtx.GoodsSrv.GoodsStock(l.ctx, &goods.GoodsStockRequest{GoodsId: int64(req.GoodsId)})
	if err != nil {
		return &types.ResMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	if stock.GoodsStock < req.Num {
		return &types.ResMsgResponse{
			Cre:  -2,
			Msg:  "库存不足",
			Data: nil,
		}, err
	}

	//添加购物车
	add, err := l.svcCtx.CartSrv.CartAdd(l.ctx, &cart.AddCartRequest{
		GoodsId:     show.GoodId,
		Num:         req.Num,
		GoodsTitle:  show.GoodsTitle,
		GoodsPrice:  show.GoodsPrice,
		GoodsAvatar: show.GoodsAvatar,
		UserId:      int64(userId),
	})
	if err != nil {
		return &types.ResMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	return &types.ResMsgResponse{
		Cre: 0,
		Msg: "添加成功",
		Data: map[string]interface{}{
			"cartId": add.CartId,
		},
	}, err
}
